// useCesiumDrawArea.ts
import { onUnmounted, ref } from 'vue';
import {
  CallbackProperty,
  Cartesian3,
  Cartographic,
  Color,
  Entity,
  Math as CesiumMath,
  PropertyBag,
  ScreenSpaceEventHandler,
  ScreenSpaceEventType,
  Viewer
} from 'cesium';

interface AreaDrawingOptions {
  viewer: Viewer;
  onDrawStart?: () => void;
  onDrawEnd?: (positions: Cartesian3[]) => void;
  onAreaAdded?: (entity: Entity) => void;
  onAreaRemoved?: (entity: Entity) => void;
  onPointAdded?: (position?: string) => void;
  onPointRemoved?: (entity: Entity) => void;
  onPointUpdated?: (entity: Entity) => void;
}

const useCesiumDrawArea = (options: AreaDrawingOptions) => {
  const { viewer, onDrawStart, onDrawEnd, onAreaAdded, onAreaRemoved, onPointAdded, onPointRemoved, onPointUpdated } = options;

  const isDrawing = ref(false);
  const isDrawingPoints = ref(false);
  const tempPositions = ref<Cartesian3[]>([]);
  const tempEntity = ref<Entity | null>(null);
  const drawnAreas = ref<Entity[]>([]);
  const concentrationPoints = ref<Entity[]>([]);
  const handler = ref<ScreenSpaceEventHandler | null>(null);
  const helpMessage = ref('');
  const selectedPoint = ref<Entity | null>(null);
  const tooltipVisible = ref(false);
  const tooltipPosition = ref({ x: 0, y: 0 });
  const tooltipMessage = ref('');
  // 创建工具提示元素
  const createTooltip = () => {
    const tooltip = document.createElement('div');
    tooltip.id = 'cesium-drawing-tooltip';
    tooltip.style.position = 'absolute';
    tooltip.style.zIndex = '9999';
    tooltip.style.pointerEvents = 'none';
    tooltip.style.backgroundColor = 'rgba(0,0,0,0.7)';
    tooltip.style.color = 'white';
    tooltip.style.padding = '5px 10px';
    tooltip.style.borderRadius = '3px';
    tooltip.style.transform = 'translate(10px, 10px)';
    tooltip.style.maxWidth = '200px';
    tooltip.style.display = 'none';
    document.body.appendChild(tooltip);
    return tooltip;
  };

  const tooltipElement = createTooltip();

  // 更新工具提示位置
  const updateTooltipPosition = (x: number, y: number) => {
    tooltipPosition.value = { x, y };
    tooltipElement.style.left = `${x}px`;
    tooltipElement.style.top = `${y}px`;
  };

  // 显示工具提示
  const showTooltip = (message: string) => {
    tooltipMessage.value = message;
    tooltipElement.textContent = message;
    tooltipElement.style.display = 'block';
    tooltipVisible.value = true;
  };

  // 隐藏工具提示
  const hideTooltip = () => {
    tooltipElement.style.display = 'none';
    tooltipVisible.value = false;
  };
  // 在鼠标移动时更新工具提示位置
  const setupTooltipTracking = () => {
    const canvas = viewer.canvas;
    canvas.addEventListener('mousemove', (e) => {
      if (tooltipVisible.value) {
        updateTooltipPosition(e.clientX, e.clientY);
      }
    });
  };

  // 初始化时设置工具提示跟踪
  setupTooltipTracking();

  //设置提示信息
  const showHelpMessage = (message: string) => {
    helpMessage.value = message;
    showTooltip(message);
  };

  //清除提示信息
  const clearHelpMessage = () => {
    helpMessage.value = '';
    hideTooltip();
  };
  // 设置鼠标样式
  const setCursor = (cursor: string) => {
    console.log('设置鼠标样式', viewer);
    const container = viewer.canvas;
    if (container) {
      container.style.cursor = cursor;
    }
  };

  // 开始绘制区域
  const startDrawing = () => {
    if (isDrawing.value) return;

    isDrawing.value = true;
    tempPositions.value = [];
    setCursor('crosshair');
    showHelpMessage('点击地图开始绘制区域，右键结束绘制');

    if (onDrawStart) {
      onDrawStart();
    }

    // 初始化事件处理器
    handler.value = new ScreenSpaceEventHandler(viewer.canvas);

    // 左键点击添加点
    handler.value.setInputAction((event: any) => {
      const position = viewer.scene.pickPosition(event.position);
      if (!position) return;

      tempPositions.value.push(position);

      // 创建临时实体
      if (tempPositions.value.length === 1) {
        tempEntity.value = viewer.entities.add({
          polygon: {
            hierarchy: new CallbackProperty(
              () => ({
                positions: tempPositions.value
              }),
              false
            ),
            material: Color.GREEN.withAlpha(0.5),
            outline: true,
            outlineColor: Color.WHITE
          }
        });
      }
    }, ScreenSpaceEventType.LEFT_CLICK);

    // 鼠标移动更新最后一个点
    handler.value.setInputAction((event: any) => {
      if (tempPositions.value.length === 0) return;

      const position = viewer.scene.pickPosition(event.endPosition);
      if (!position) return;

      if (tempPositions.value.length > 1) {
        tempPositions.value.pop();
      }
      tempPositions.value.push(position);
    }, ScreenSpaceEventType.MOUSE_MOVE);

    // 右键结束绘制
    handler.value.setInputAction(() => {
      if (tempPositions.value.length < 3) {
        cancelDrawing();
        showHelpMessage('至少需要3个点来创建区域');
        setTimeout(clearHelpMessage, 2000);
        return;
      }

      finishDrawing();
    }, ScreenSpaceEventType.RIGHT_CLICK);
  };

  // 开始绘制浓度点位
  const startDrawingPoints = () => {
    if (isDrawingPoints.value) return;

    isDrawingPoints.value = true;
    setCursor('crosshair');
    showHelpMessage('点击地图添加浓度点位，右键结束绘制');

    if (onDrawStart) {
      onDrawStart();
    }

    // 初始化事件处理器
    handler.value = new ScreenSpaceEventHandler(viewer.canvas);

    // 左键点击添加点
    handler.value.setInputAction((event: any) => {
      const position = viewer.scene.pickPosition(event.position);
      if (!position) return;

      addConcentrationPoint(position);
    }, ScreenSpaceEventType.LEFT_CLICK);

    // 右键结束绘制
    handler.value.setInputAction(() => {
      stopDrawingPoints();
    }, ScreenSpaceEventType.RIGHT_CLICK);
  };
  // 添加坐标转换方法
  const cartesianToLonLat = (cartesian: Cartesian3): string => {
    const cartographic = Cartographic.fromCartesian(cartesian);
    return String(CesiumMath.toDegrees(cartographic.longitude)) + ',' + String(CesiumMath.toDegrees(cartographic.latitude));
  };
  // 添加浓度点位
  const addConcentrationPoint = (position: Cartesian3) => {
    // concentrationPoints.value.push(point);
    if (onPointAdded) {
      onPointAdded(cartesianToLonLat(position));
    }
  };
  // 更新浓度点位
  const updateConcentrationPoint = (entity: Entity, newPosition?: Cartesian3, newConcentration?: number) => {
    if (newPosition) {
      entity.position = newPosition as any;
    }

    if (newConcentration !== undefined) {
      entity.properties = entity.properties || ({} as PropertyBag);
      entity.properties.concentration = newConcentration;
    }

    if (onPointUpdated) {
      onPointUpdated(entity);
    }
  };

  // 删除浓度点位
  const removeConcentrationPoint = (entity: Entity) => {
    const index = concentrationPoints.value.indexOf(entity);
    if (index !== -1) {
      viewer.entities.remove(entity);
      concentrationPoints.value.splice(index, 1);
      if (onPointRemoved) {
        onPointRemoved(entity);
      }
    }
  };

  // 停止绘制浓度点位
  const stopDrawingPoints = () => {
    if (handler.value) {
      handler.value.destroy();
      handler.value = null;
    }

    isDrawingPoints.value = false;
    setCursor('auto');
    clearHelpMessage();
  };

  // 结束绘制并保存区域
  const finishDrawing = () => {
    if (!isDrawing.value || tempPositions.value.length < 3) return;

    const positions = [...tempPositions.value];

    // 创建最终实体
    const entity = viewer.entities.add({
      polygon: {
        hierarchy: positions,
        material: Color.BLUE.withAlpha(0.5),
        outline: true,
        outlineColor: Color.WHITE,
        outlineWidth: 2
      }
    });

    drawnAreas.value.push(entity);

    if (onAreaAdded) {
      onAreaAdded(entity);
    }

    if (onDrawEnd) {
      onDrawEnd(positions);
    }

    cleanupDrawing();
  };

  // 取消绘制
  const cancelDrawing = () => {
    cleanupDrawing();
  };

  // 清理绘制状态
  const cleanupDrawing = () => {
    if (handler.value) {
      handler.value.destroy();
      handler.value = null;
    }

    if (tempEntity.value) {
      viewer.entities.remove(tempEntity.value);
      tempEntity.value = null;
    }

    tempPositions.value = [];
    isDrawing.value = false;
    setCursor('auto');
    clearHelpMessage();
  };

  // 删除所有绘制的区域
  const clearAllAreas = () => {
    drawnAreas.value.forEach((entity) => {
      viewer.entities.remove(entity);
      if (onAreaRemoved) {
        onAreaRemoved(entity);
      }
    });
    drawnAreas.value = [];
  };

  // 删除所有浓度点位
  const clearAllPoints = () => {
    concentrationPoints.value.forEach((entity) => {
      viewer.entities.remove(entity);
      if (onPointRemoved) {
        onPointRemoved(entity);
      }
    });
    concentrationPoints.value = [];
  };

  // 删除指定区域
  const removeArea = (entity: Entity) => {
    const index = drawnAreas.value.indexOf(entity);
    if (index !== -1) {
      viewer.entities.remove(entity);
      drawnAreas.value.splice(index, 1);
      if (onAreaRemoved) {
        onAreaRemoved(entity);
      }
    }
  };

  // 组件卸载时清理
  onUnmounted(() => {
    if (tooltipElement && tooltipElement.parentNode) {
      tooltipElement.parentNode.removeChild(tooltipElement);
    }
    cleanupDrawing();
    stopDrawingPoints();
    clearAllAreas();
    clearAllPoints();
  });

  return {
    isDrawing,
    isDrawingPoints,
    helpMessage,
    drawnAreas,
    concentrationPoints,
    selectedPoint,
    startDrawing,
    startDrawingPoints,
    finishDrawing,
    cancelDrawing,
    stopDrawingPoints,
    clearAllAreas,
    clearAllPoints,
    removeArea,
    addConcentrationPoint,
    updateConcentrationPoint,
    removeConcentrationPoint
  };
};
export default useCesiumDrawArea;
